<template>
  <div style="height: 100%;background-color:white ;">
    <DataPermissionDialog ref="dataPermissionDialog" :roleId="crtRole.id" :roleName="crtRole.roleName"/>
    <el-row>
      <el-col :span="12">
        <el-button size="small" type="success" @click="editRole(null)">新建角色
        </el-button>
      </el-col>
      <el-col :span="12" style="right: auto">
        <div>
          <div style="width: 430px; float: right">
            <el-input v-model="roleName" placeholder="请输入角色名" size="small" @keyup.enter.native="getTableData">
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-button slot="append" :icon="appendIcon" v-on:click="switchAppend"></el-button>
            </el-input>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <div>
        <el-table :data="tableData" :height="tableHeight" border stripe style="width: 100%;margin-top: 10px">
          <el-table-column label="角色名称" min-width="80" prop="roleName"></el-table-column>
          <el-table-column label="拥有的权限" min-width="300" prop="resourceName"></el-table-column>
          <el-table-column label="备注" min-width="80" prop="remark"></el-table-column>
          <el-table-column label="启用状态" width="100" prop="status">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.status"
                active-value="true"
                inactive-value="false"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <span><el-link type="success"
                             @click.prevent="editRole(scope.row)">编辑</el-link></span>
              <span><el-link type="success"
                             @click.prevent="authorityEdit(scope.row.id)">权限编辑</el-link></span>
              <span><el-link type="danger"
                             @click.prevent="del(scope.row.id)">删除</el-link></span>
              <span><el-link type="success"
                             @click.prevent="editDataPermission(scope.row)">数据权限</el-link></span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>

    <el-dialog :title="roleType" :visible.sync="newRoleDialogVisible" top="15px"
               width="500px"
               @click="closeNewDialog">
      <el-row>
        <el-col :span="6">
          <span class="label">角色名<em style="color: red">*</em></span>
        </el-col>
        <el-col :span="18">
          <el-input v-model="role.roleName" placeholder="请输入名称"/>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">备注</span>
        </el-col>
        <el-col :span="18">
          <el-input v-model="role.remark" placeholder="请输入备注"></el-input>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">启用状态</span>
        </el-col>
        <el-col :span="18">
          <el-switch v-model="role.status" class="form-switch"></el-switch>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeNewDialog">取 消</el-button>
        <el-button type="primary" @click="newRole()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" title="权限编辑" top="15px"
               width="650px"
               @click="closeDialog">

      <el-table
        ref="multiTable"
        :data="roleData"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        border
        default-expand-all
        height="500px"
        row-key="id"
        @select="handleSelect">
        <el-table-column
          v-model="multipleSelection"
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="名称"
          prop="name"
          sortable
          width="240">
        </el-table-column>
        <el-table-column
          label="操作"
          prop=""
          sortable
          width="300">
          <template slot-scope="scope">
            <el-checkbox
              v-if="CONST.AUTHORITY_EDIT_LIST.find(item=>item===scope.row.id)"
              v-model="scope.row.detailButton">详情
            </el-checkbox>
            <el-checkbox
              v-if="CONST.AUTHORITY_EDIT_LIST.find(item=>item===scope.row.id)"
              v-model="scope.row.editButton">编辑
            </el-checkbox>
            <el-checkbox v-if="CONST.AUTHORITY_PUSH_LIST.find(item=>item===scope.row.id)"
                         v-model="scope.row.pushButton">推送
            </el-checkbox>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer" style="right: auto">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import DataPermissionDialog from "../user/DataPermissionDialog";
export default {
  name: "RoleTable",
  components: {DataPermissionDialog},
  data() {
    return {
      crtRole: {},
      tableData: [],
      tableHeight: 100,
      multiplePages: true,
      appendIcon: "el-icon-caret-bottom",
      noData: true,
      totalNum: 0,
      showAdvance: false,
      currentPage: 0, // 第几页
      pageSize: 10, // 每页显示的数据个数
      newRoleDialogVisible: false,
      dialogVisible: false,
      roleType: '新建',
      roleName: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      name: '',
      roleData: [],
      role: {},
      resourceIds: [],
      resourceName: '',

      roleId: '',
      checkList: [],
      multipleSelection: [],
    }
  },
  methods: {
    editDataPermission(crtRole) {
      this.crtRole = crtRole
      this.$refs.dataPermissionDialog.visible = true
    },
    handleCheckChange(node, flag) {
      // 选中节点, 则同时选中父节点;
      if (flag) {
        if (node.parentId) {
          this.$refs.roleTree.setChecked(node.parentId, true, false)
        }
      }
      // 取消选中节点, 同时取消子节点选中状态;
      else {
        this.$refs.roleTree.setChecked(node, false)
        node.children.forEach(node => this.$refs.roleTree.setChecked(node, false))
      }
    },
    editAuthority(id) {
      this.$router.push({
        path: "/resourceTable",
        query: {roleId: id}
      })
    },
    editRole(row) {
      if (row) {
        this.roleType = '编辑'
        this.resourceIds = JSON.parse(row.resourceId)
        console.log(this.resourceIds)
        this.role = JSON.parse(JSON.stringify(row))
        if (row.status == 'true') {
          this.role.status = true;
        } else {
          this.role.status = false;
        }
      } else {
        this.roleType = '新建'
        this.resourceIds = []
        this.role = {}
      }


      this.newRoleDialogVisible = true
    },
    del(id) {
      this.$confirm('您确认要删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        let param = new URLSearchParams();
        param.append("id", id)
        this.axios.post(CONST.SERVICE_REST_PACKAGE + "RoleCtrl/delete", param).then(() => {
          this.getTableData()
        })
      })
    },

    getResource() {
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "RoleCtrl/selectResource", {
        params: {}
      }).then((response) => {
        this.roleData = response.data
        console.log(this.roleData)
      })
    },
    newRole() {
      if (UTIL.isEmpty(this.role.roleName)) {
        this.$message.warning("请输入角色名");
        return;
      }
      let param = JSON.parse(JSON.stringify(this.role))
      this.axios.post(CONST.SERVICE_REST_PACKAGE + "RoleCtrl/saveBean", param)
        .then(() => {
          this.closeNewDialog()
          this.getTableData()
          this.newRoleDialogVisible = false
        })
    },
    getTableData() {
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "RoleCtrl/selectTableData", {
        params: {
          roleName: this.roleName,
        }
      }).then((response) => {
        this.tableData = response.data
        console.log(response.data[0].status)
      })
    },
    closeNewDialog() {
      this.role = {}
      this.resourceIds = []
      this.newRoleDialogVisible = false
    },
    closeDialog() {
      this.multipleSelection = []
      this.$refs.multiTable.clearSelection()
      this.roleId = ''
      this.dialogVisible = false
    },

    advanceCancel() {
      this.showAdvance = false;
    },
    replacement: function () {
      this.userName = '';
      this.name = ''
    },
    advanceConfirm() {
      this.getTableData();
      this.showAdvance = false;
    },
    switchAppend: function () {
      if (this.showAdvance) {
        this.showAdvance = false;
        this.appendIcon = "el-icon-caret-bottom";
      } else {
        this.showAdvance = true;
        this.appendIcon = "el-icon-caret-top";
      }
    },
    handleCurrentChange: function (val) {
      this.currentPage = val - 1;
      this.getTableData();
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.getTableData()
    },

    authorityEdit(id) {
      this.getAuthorityData(id)
      this.dialogVisible = true
      this.roleId = id
      this.$refs.multiTable.clearSelection()
      let that = this
      UTIL.recursiveForEachTreeNode(this.$refs.multiTable.tableData, item => {
        that.$set(item, 'pushButton', false)
        that.$set(item, 'editButton', false)
        that.$set(item, 'detailButton', false)

      })
    },
    handleSelect(selection, row) {
      // 如果selection中存在row代表是选中，否则是取消选中
      if (selection.find(val => {
        return val.name === row.name
      })) {
        if (row.children) {
          row.children.forEach(val => {
            this.$refs.multiTable.toggleRowSelection(val, true)
            selection.pushIfNotContains(val)
            if (val.children.length > 0) {
              this.handleSelect(selection, val)
            }
          })
        }
        this.selectFu(selection, row, this.roleData)
      } else {
        this.cleanSelections(selection, row)
      }
      //选中子节点对应父节点选中
      console.log(selection)
      this.multipleSelection = selection
    },
    cleanSelections(selection, row) {
      if (row.children.length > 0) {
        row.children.forEach(val => {
          selection.forEach(s => {
            if (s.id === val.id) {
              this.$refs.multiTable.toggleRowSelection(val, false)
              selection.splice(val, 1)
            }
          })
          if (val.children.length > 0) {
            this.cleanSelections(selection, val)
          }
        })
      }
    },
    selectFu(selection, row, data) {
      if (data.find(item => {
        if (item.id === row.parentId) {
          this.$refs.multiTable.toggleRowSelection(item, true)
          selection.pushIfNotContains(item)
          this.selectFu(selection, item, data)
        }
        if (item.children.length > 0) {
          this.selectFu(selection, row, item.children)
        }
        // selection.forEach(s => {
        //   if (s.parentId === item.id) {
        //     this.$refs.multiTable.toggleRowSelection(item, true)
        //     selection.pushIfNotContains(item)
        //   }
        // })
      })) ;
    },
    confirm() {
      let param = new URLSearchParams();
      param.append("selection", JSON.stringify(this.multipleSelection))
      param.append("roleId", this.roleId)
      this.axios.post(CONST.SERVICE_REST_PACKAGE + "RoleCtrl/save", param)
        .then(() => {
          this.closeDialog()
          this.getTableData()
          this.dialogVisible = false
          this.multipleSelection = []
        })
    },
    getAuthorityData(id) {
      this.multipleSelection = [];
      this.axios.get(CONST.SERVICE_REST_PACKAGE + "RoleCtrl/selectAuthorityTableData", {
        params: {
          roleId: id,
        }
      }).then((response) => {

        if (response.data.length > 0) {
          for (let i = 0; i < response.data.length; i++) {
            var findTreeNode = UTIL.findTreeNode(this.$refs.multiTable.tableData, item => item.id === response.data[i].id);
            findTreeNode.pushButton = response.data[i].pushButton === 1
            findTreeNode.editButton = response.data[i].editButton === 1
            findTreeNode.detailButton = response.data[i].detailButton === 1

            this.$refs.multiTable.toggleRowSelection(findTreeNode, true)
            this.multipleSelection.pushIfNotContains(findTreeNode)

          }
        }
      })
    },
  }
  ,
  created() {
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 95;
    this.getTableData()
    this.getResource()
  }
}
</script>

<style scoped>

</style>
